window.onload= async function (){
    //页面加载完成 执行 同步操作 获取  全部全部班级列表
    majorlist= await majorlist.then(res=>{
        return res
    })

   console.log(majorlist)
    //加载编辑的按钮打开的模态吗中的子元素
    for (let i=1,len=majorlist.length+1;i<len;i++){
        let elem =`
                <div class="input-group mb-3">
                  <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1">第${i}志愿</span>
                  </div>
                  <select id="editWish${i}" type="text" index='${i-1}' class="form-control wish" aria-label="first" aria-describedby="basic-addon1">
                  </select>
                </div>
                `
        $('#editModal .modal-body').append(elem)
    }


    axios.defaults.headers.common.token = localStorage.getItem('admin_token')



    var $table = $('#table')
    var $column =[]
    var $data = []


    var wishList = ['']
    for (let i of majorlist){
        wishList.push(i)
    }
    console.log(wishList)
    // 输出为 wishList = ['','vr','php','网络','游戏','java','ui','大数据']




    var choiceList=[]
    var config=[]
    uploadKeyMap=[]
    axios.all([axios.get('/api/config'),axios.get('/api/admin/students?all=1')])
        .then(function(res){
          console.log(res)
            config = res[0].data
            $column = JSON.parse(config.field)
             //添加当前的所有的志愿
            for(let i=0,len=majorlist.length;i<len;i++){
              $column.push({"title":`第${i+1}志愿`,"field":`wish${i+1}`})
            }
            console.log($column)
            $data = res[1].data[0].data
            //将 全部学生的列表存起来
            oldAllStuList=JSON.parse(JSON.stringify($data))
            load()
        })

    function load(){
        $column.push({field:'Button编辑',title:'操作',events:operateEvents,formatter:AddButton})
         console.log($column)
        $table.bootstrapTable('refreshOptions', {
            height:$(window).height(),
            searchAlign:'left',
            data:$data,
            columns:$column})
    }

    // 搜索函数
    customSearch= function (data, text) {
        console.log('------------')
        let customField = document.getElementById('customSearch').value
        if(customField == 'price'){
            return data.filter(function (row) {
                return row.price.indexOf(text) > -1
            })
        }else if(customField == 'name'){
            return data.filter(function (row) {
                return row.name.indexOf(text) > -1
            })
        }else if(customField == 'stu_id'){
            return data.filter(function (row) {
                return row.stu_id.indexOf(text) > -1
            })
        }else if(customField == 'subject'){
            return data.filter(function (row) {
                return row.subject.indexOf(text) > -1
            })
        }else if(customField == 'class_base'){
            return data.filter(function (row) {
                return row.class_base.indexOf(text) > -1
            })
        }else if(customField == 'class_new_id'){
            return data.filter(function (row) {
                try{
                    return row.class_new_id.indexOf(text) > -1
                }catch(e){
                    return false
                }
            })
        }else if(customField == 'class_first_id'){
            return data.filter(function (row) {
                try{
                    return row.class_first_id.indexOf(text) > -1
                }catch(e){
                    return false
                }
            })
        }
    }
//返回操作按钮列
    function AddButton(value,row,index){
        return ['<button id="TableEditor" class="btn  btn-success"> 编辑</button>'].join("")
    }
// 编辑按钮事件
    operateEvents = {"click #TableEditor":function(e,value,row,index){
            $('#editModal').modal('show')
            editData = $table.bootstrapTable('getData')[index]
            console.log(editData)
            $('#editIndex')[0].value = index
            $('#editStuid')[0].value = editData.stu_id
            $('#editName')[0].value = editData.name
            $('#editClass')[0].value = editData.class_base
            $('#editPhp')[0].value = editData.score_php
            $('#editPython')[0].value = editData.score_python
            // for (let i in )
            for (let i=1,len=majorlist.length+1;i<len;i++){
                let item=editData['wish'+i];
                if (item){
                    $('#editWish'+i)[0].value = item
                    console.log( $('#editWish'+i)[0].value)
                }
            }
            $('#editClass2')[0].value = editData.class_new_id
        }}

// 保存修改
    $('#editSave').on('click',function(){
        // 获取修改后的值
        //暂停
        php = $('#editPhp')[0].value
        python = $('#editPython')[0].value
        index =  $('#editIndex')[0].value
        stuid =  $('#editStuid')[0].value
        name =  $('#editName')[0].value
        class_new_id =  $('#editClass2')[0].value
        newwish= {};
        for (let i=1,len=wishList.length+1;i<len;i++){
            item =$('#editWish'+i)[0]
            if (item){
                item=item.value
            }
            if (item){
                newwish['wish'+i]=item;
            }
        }
        console.log(newwish)
        //判断是否满足专业数量
        let newlen=Object.values(newwish).length//新的志愿数
        let majorlistLen=Object.keys(majorlist).length//所有专业数
        if (newlen !==majorlistLen){
            alert('缺少'+(majorlistLen-newlen)+'个志愿')
            return;
        }
        let set = new Set(Object.values(newwish))
        console.log(set)
        if (set.size !== newlen){
            alert(majorlistLen+'个志愿不能一样')
            return
        }
        updata={
            stu_id:stuid,
            name:name,
            score_python:python,
            score_php:php,
            class_new_id:class_new_id,
            wish:{
               ...newwish
            }
        }
        console.log(updata)
        axios.put('/api/admin/score_wish',{"score_wish":[updata]})
            .then(function(res){
                console.log(res)
                if(res.data.error){
                    alert (res.data.error)
                }else{
                    alert(res.data.message)
                    $('#editModal').modal('hide')
                    for (let i in newwish){
                        $data[index][i]=newwish[i];
                    }
                    $data[index].php = php
                    $data[index].python = python
                    $data[index].class_new_id = class_new_id
                    $table.bootstrapTable('refreshOptions',{data:$data})
                }
            })
            .catch(function(){})
    })


// 导入部分
    let btnUpdata = document.querySelector('#btnUpdata');
    let inpUpdata = document.querySelector('#inpUpdata');
    inpUpdata.addEventListener('change',(e)=>{
        excelUpload(e,(res)=>{
            // 刷新表格设置展示excel数据
            console.log(JSON.stringify(res.data));

            data = res.data
            var excelkeyMap = {
                "stu_id":'学号',
                "name":'姓名',
                "idnum":'身份证号',
                "class_base":'大一班级',
                "subject":'所学专业',
                "stu_type":'生源类型',
                "score_python":'Python成绩',
                "score_php":'PHP成绩'
            }
            keyMap = config.upload
            newData =[]
            for(itme of data){
                var objs= Object.keys(itme).reduce((newData, key) => {
                    let newKey = keyMap[key] || key
                    newData[newKey] = itme[key]
                    return newData
                }, {})
                newData.push(objs)
            }

            $('#btnUpdata').html('返回')
            $('#btnUpdata').attr('back',1)

            let Newcolumns = []
            let keys = Object.keys(newData[0])


            for(let i =0 ;i <keys.length;i++){
                Newcolumns.push({"title":excelkeyMap[keys[i]],"field":keys[i]})
            }

            $table.bootstrapTable('refreshOptions',{
                height:$(window).height(),
                data:newData,
                columns:Newcolumns
            })
            $('.bs-bars').width(600)
            $('#btnUpdata').removeAttr('for')

        })
    })

    $(btnUpdata).on('click',function(){
        if($(this).attr('back') ==1){
            $table.bootstrapTable('refreshOptions',{
                height:$(window).height(),
                data:$data,
                columns:$column
            })
            $('#inpUpdata').val('')
            $('.bs-bars').width(600)

            $('#btnUpdata').html('导入')
            setTimeout(() => {
                $('#btnUpdata').attr('for','inpUpdata')
            }, 10);
        }
    })

    // 保存Excel导入的数据
    $('#saveExcel').on('click',function(){
        // console.log($table.bootstrapTable('getData'))
        let newAllStuList=$table.bootstrapTable('getData');
        // if (JSON.stringify($data)==JSON.stringify(oldAllStuList)){
        //     alert('数据未未改变 无法保存')
        //     return;
        // }
        // //数据  校验 及处理 start
        // let oldObj={} // 存放 旧数据
        // let newObj={} // 存放 修改后的新数据
        // for(let i of oldAllStuList){
        //     if(!i.stu_id){
        //         alert('有学生缺少 学号 请核对')
        //         return;
        //     }
        //     oldObj[i.stu_id]=i;
        // }
        // for(let i of newAllStuList){
        //     if(!i.stu_id){
        //         alert('有学生缺少 学号 请核对')
        //         return;
        //     }
        //     newObj[i.stu_id]=i;
        // }
        //
        // let objStuList={};
        // //循环 旧数据 和 新数据的学号
        // for( let i of [...Object.keys(oldObj),...Object.keys(newObj)]){
        //     let newStu=newObj[i];
        //     let oldStu=oldObj[i];
        //     if(newStu){
        //         for (let k in newStu){
        //             if (!newStu[k]&&newStu[k]!=0){
        //                 delete newStu[k]
        //             }
        //         }
        //     }else {
        //         newStu={}
        //     }
        //     if (oldStu){
        //         for (let k in oldStu){
        //             if (!oldStu[k]&&oldStu[k]!=0){
        //                 delete oldStu[k]
        //             }
        //         }
        //     }else {
        //         oldStu={}
        //     }
        //     objStuList[i]={...oldStu,...newStu};
        // }
        // //处理完成
        // console.log('我要打断')
        // let data=Object.values(objStuList)
        axios.post('/api/admin/students',{"students":JSON.stringify(newAllStuList)})
            .then(function(response){
                res = response.data
                console.log(response)
                if(res.error){
                    alert(res.error)
                }else{
                    alert('保存成功')
                    location.reload();
                    return
                    $('#inpUpdata').val('')
                    axios.get('/api/admin/students?all=1')
                        .then(function(response){
                            $data = response.data[0].data
                            $table.bootstrapTable('refreshOptions', {
                                height:$(window).height(),
                                searchAlign:'left',
                                data: response.data[0].data,
                                columns:$column
                            })
                            $('.bs-bars').width(600)
                        })
                        .catch(function(){})
                }
            })
            .catch(function(){})
    })

// 添加修改Select change事件
    wishSelect = $('select.wish')
    for(let i = 0;i<wishSelect.length;i++){
        for(let j =0 ;j <wishList.length;j++){
            $(wishSelect[i]).append(`<option value='${wishList[j]}'>${wishList[j]}</option>`)
        }
    }


    for(let i = 0;i<wishSelect.length;i++){
        $(wishSelect[i]).change(function(){
            choiceList[$(wishSelect[i]).attr('index')] = this.value

        })
    }

    function removeRepeat(){
        return choiceList.filter(function(item,index){
            return wishList.indexOf(item) == -1
        })
    }


    $('#editproportion').on('click',function () {
        axios.get('/api/config')
            .then(function(res){
                scorerule = res.data.scorerule
                $('#phpproportion')[0].value = scorerule.score_php*100
                $('#pythonproportion')[0].value = scorerule.score_python*100
            })
    })

    $('#saveproportion').on('click',function(){
        php_rule = $('#phpproportion')[0].value/100
        python_rule = $('#pythonproportion')[0].value/100

        console.log(php_rule)
        console.log(python_rule)
        return

        axios.post('/api/admin/scorerule',{rule:{score_python:python_rule,score_php:php_rule}})
            .then(function (res) {
                if(res.data.error){
                    alert(res.data.error)
                }else{
                    alert(res.data.message)
                    axios.get('/api/admin/students?all=1')
                        .then(function(response){
                            data = response.data[0].data[0]
                            $table.bootstrapTable('refreshOptions', {
                                height:$(window).height(),
                                searchAlign:'left',
                                data: response.data[0].data,
                                columns:$column
                            })
                            $('.bs-bars').width(600)

                        })
                        .catch(function(){})
                    $('#proportion').modal('hide')
                }
            })
    })


    $('#StartChange').on('click',function(){
        console.log($('#StartPass')[0].value)
    })


    var clist;
    axios.get('/api/admin/class2').then(function(res){
        (clist = res.data)

        for(let i = 0 ;i < clist.length;i++){
            $('#editClass2').append(`<option value='${clist[i].name}'>${clist[i].name}</option>`)
        }
    })

    $('#startChange').on('click',function(){
        conf = confirm('确认开始分班？')
        if(conf){
            alert('分班已经开始，请稍等')

            axios.get('/api/admin/classchanges').then(function(res){
                console.log(res)
                if(!res.data.error){
                    alert(res.data.message)
                    $(function() {
                        let columns = []
                        axios.get('/api/admin/students?all=1')
                            .then(function(response){
                                $data = response.data[0].data
                                $table.bootstrapTable('refreshOptions', {
                                    height:$(window).height(),
                                    searchAlign:'left',
                                    data: $data,
                                    columns:$column
                                })
                                $('.bs-bars').width(600)

                            })
                            .catch(function(){})
                    })
                }else{
                    alert(res.data.error)
                }
            })
        }
    })




}

